package coms.dataaccess.hibernate;

import coms.dataaccess.dao.ConferenceDAO;
import coms.dto.Conference;
import coms.dto.ConferenceRegistration;
import coms.dto.User;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

public class ConferenceDAOImpl extends GenericDAOImpl<Conference, Integer> implements ConferenceDAO {

    private Session session;

    @Override
    public List<Conference> searchConferenceByParticipant(User user) {
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(ConferenceRegistration.class, "confReg");
        if (user!= null){
            criteria.createAlias("confReg.participant", "p")
                    .add(Restrictions.eq("p.id", user.getId()));
        }
        criteria.setProjection(Projections.property("confReg.conference"));
        List<Conference> confList = criteria.list();
        clear();
        return confList;
    }

    @Override
    public List<Conference> search(Conference conference) throws SQLException {
       session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(Conference.class, "conf");
        if (conference == null) return criteria.list();
        
         if (conference.getName()!=null && !conference.getName().equals("")){
            criteria.add(Restrictions.like("conf.name", "%"+conference.getName()+"%"));
        }
        
        if (conference.getLocation()!= null){
            criteria.createAlias("conf.location", "loc")
                    .add(Restrictions.eq("loc.id", conference.getLocation().getId()));
        }
        
        if (conference.getConferenceStartDate()!=null){
            criteria.add(Restrictions.ge("conf.conferenceStartDate", conference.getConferenceStartDate()));
        }
        
        if (conference.getConferenceEndDate()!=null){
            criteria.add(Restrictions.le("conf.conferenceEndDate", conference.getConferenceEndDate()));
        }
        
        List<Conference> confList = criteria.list();
        clear();
        return confList;
    }
}
